﻿using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using SW.DDD.Domain;
using SW.DDD.Infrastructure;

namespace SW.DDD.Application.Query
{
    /// <summary>
    /// 查询处理类
    /// </summary>
    /// <typeparam name="TView">要返回的视图类型</typeparam>
    /// <typeparam name="TEntity">来源实体类型</typeparam>
    /// <typeparam name="TKey">实体键</typeparam>
    public class QueryHandler<TView, TEntity, TKey> : IQueryHandler<Query<TView, TEntity, TKey>, (IEnumerable<TView>, int?)>
        where TEntity : class, IAggregateRoot<TKey>
        where TKey : notnull
    {
        protected IRepository<TEntity, TKey> Repository { get; }

        protected IMapper Mapper { get; }

        public QueryHandler(IRepository<TEntity, TKey> repository, IMapper mapper)
        {
            Repository = repository;
            Mapper = mapper;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual async Task<(IEnumerable<TView>, int?)> Handle(Query<TView, TEntity, TKey> request, CancellationToken cancellationToken)
        {
            var data = await Repository.QueryAsync(qy =>
            {
                if(request.BaseQueryPlan != null)
                    qy = request.BaseQueryPlan(qy);
                var models = Mapper.ProjectTo<TView>(qy, request.Parameters);
                return request.QueryExpression.ExecuteQuery(models);
            });

            if(!request.NeedCount)
                return (data, null);

            var count = await Repository.CountAsync(qy =>
            {
                if(request.BaseQueryPlan != null)
                    qy = request.BaseQueryPlan(qy);
                var models = Mapper.ProjectTo<TView>(qy);
                return request.QueryExpression.ExecuteWhere(models);
            });

            return (data, count);
        }
    }
}
